package euler.p001_050;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

import euler.MainEuler;
import euler.helper.Utils;

public class Euler022 extends MainEuler {

    /*
        Using http://projecteuler.net/project/names.txt
        begin by sorting it into alphabetical order.
        Then working out the alphabetical value for each name,
        multiply this value by its alphabetical position
        in the list to obtain a name score.

        For example, when the list is sorted into alphabetical
        order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53,
        is the 938th name in the list.
        So, COLIN would obtain a score of 938 × 53 = 49714.

        What is the total of all the name scores in the file?

     */
    public String resolve() throws IOException {

        String filePath = Utils.pathToFiles + "names.txt";

        BufferedReader br = null;
        String strLine;

        try {
            br = new BufferedReader(new FileReader(new File(filePath)));
            strLine = br.readLine();
        } finally {
            if (br != null) {
                br.close();
            }
        }

        String[] split = strLine.split("\",\"");

        split[0] = split[0].substring(1);
        split[split.length-1] = split[split.length-1].substring(0,split[split.length-1].length()-1);

        Arrays.sort(split);

        int sum = 0;
        for (int i = 0; i < split.length; i++) {
            sum+=((i + 1) * alphabeticalValue(split[i]));
        }

        return String.valueOf(sum);
    }

    private static final int offset = 'A' - 1;
    private int alphabeticalValue(String s) {
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            sum+=(s.charAt(i) - offset);
        }
        return sum;
    }

}
